package com.smile.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smile.api.OperateLogApi;
import com.smile.api.OrganizationApi;
import com.smile.api.OssApi;
import com.smile.commons.error.ErrorCodeUtil;
import com.smile.commons.page.MyBatisPlusPageConverter;
import com.smile.mapper.*;
import com.smile.model.domain.*;
import com.smile.model.dto.request.AddAirportRequestDTO;
import com.smile.model.dto.request.GetInspectionTaskListRequestDTO;
import com.smile.model.request.GetAirportByIdRequest;
import com.smile.model.response.Drone;
import com.smile.model.response.response.GetAirportListResponseDTO;
import com.smile.model.response.response.GetDroneByIdResponseDTO;
import com.smile.model.response.response.GetInspectionTaskListResponseDTO;
import com.smile.service.SituationScreenService;
import com.smile.service.uitl.CoordinateTransformUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SituationScreenServiceImpl implements SituationScreenService {

    @Autowired
    private OssApi ossApi;

    @Autowired
    private AirportMapper airportMapper;


    @Autowired
    private AirportInfoMapper  airportInfoMapper;
    @Autowired
    private OperateLogApi operateLogApi;

    @Autowired
    private AirportDroneMapper airportDroneMapper;

    @Autowired
    private DroneMapper droneMapper;

    @Autowired
    private FlightTaskMapper flightTaskMapper;

    @Autowired
    private FlightStatisticsMapper flightStatisticsMapper;
    @Autowired
    private InspectionTaskMapper  inspectionTaskMapper;

    private ReentrantLock reentrantLock = new ReentrantLock();


    @Override
    public Map<String,Object> resourceScheduling() throws IOException {
        Map<String, Object> map = new HashMap<>();
        //7日最新
        List<FeisuanAirport> qj = airportMapper.selectList(new QueryWrapper<FeisuanAirport>());
        List<Map<String,Object>> list = new ArrayList<>();
        List<Map<String,Object>> list2 = new ArrayList<>();
        for(FeisuanAirport feisuanAirport:qj){
            Map<String,Object> map1 = new HashMap<>();
            Map<String,Object> map2 = new HashMap<>();
            map2.put("name",feisuanAirport.getAirportName());
            map1.put("name",feisuanAirport.getAirportName());
            LocalDate today = LocalDate.now();
            LocalDate sevenDaysAgo = today.minusDays(7);
            CountFlight countFlight = flightStatisticsMapper.countFlightByAirport(feisuanAirport.getId(),sevenDaysAgo,today);
            System.out.println(countFlight);
            if(countFlight == null){
                map1.put("num",0);
                map2.put("num",0);
            }else{
                map1.put("num",String.format("%.2f", Double.valueOf( countFlight.getNum()/7)));
                map2.put("num",String.format("%.2f", Double.valueOf(countFlight.getDistance().toString())/7));
            }
            list.add(map1);
            list2.add(map2);

        }
        map.put("qj",list);
        map.put("lc",list2);
        return  map;
    }
    @Override
    public Map<String,Object> Info() throws IOException {
        Map<String,Object> map = new HashMap<>();

        List<GetAirportListResponseDTO> onlineDevice = new ArrayList<>();
        //设备总览
        Map<String,Object> device = new HashMap<>();
        QueryWrapper<FeisuanAirport> queryWrapper = new QueryWrapper<>();
        List<FeisuanAirport> airportList = airportMapper.selectList(queryWrapper);
        Integer airportNum =  airportList.size();
//        QueryWrapper<FeisuanDrone> feisuanDroneQueryWrapper = new QueryWrapper<>();
//        List<FeisuanDrone> droneList = droneMapper.selectList(feisuanDroneQueryWrapper);

        Integer airportOnlineNum = 0;
        for (FeisuanAirport feisuanAirport : airportList) {
            if(feisuanAirport.getStatus() ==1){
                Duration duration =Duration.between(feisuanAirport.getModifyTime(), LocalDateTime.now());
                if(duration.toSeconds() <10){
                    GetAirportListResponseDTO getAirportListResponseDTO= BeanUtil.copyProperties(feisuanAirport, GetAirportListResponseDTO.class);
                    QueryWrapper<FeisuanAirportInfo> feisuanAirportInfoQueryWrapper = new QueryWrapper<>();
                    feisuanAirportInfoQueryWrapper.eq("gateway_sn", feisuanAirport.getGatewaySn());
                    FeisuanAirportInfo feisuanAirportInfo = airportInfoMapper.selectOne(feisuanAirportInfoQueryWrapper);
                    if(ObjectUtil.isNotNull(feisuanAirportInfo)){
                        getAirportListResponseDTO.setModeCode(feisuanAirportInfo.getModeCode());
                        if (feisuanAirportInfo.getModeCode() == 0) {
                            getAirportListResponseDTO.setFlightStatus(0);
                        }
                        try{
                            CoordinateTransformUtil.Coordinate coordinate = CoordinateTransformUtil.wgs84ToGcj02(getAirportListResponseDTO.getLongitude(), getAirportListResponseDTO.getLatitude());
                            getAirportListResponseDTO.setLatitude(coordinate.getLatitude());
                            getAirportListResponseDTO.setLongitude(coordinate.getLongitude());
                        }catch (Exception e){
                        }
                        onlineDevice.add(getAirportListResponseDTO);
                    }
                    airportOnlineNum++;
                }
            }
        }

        device.put("airportOnlineNum",airportOnlineNum);
        device.put("airportNum",airportNum);

        QueryWrapper<FeisuanDrone> queryWrapper1 = new QueryWrapper<>();
        List<FeisuanDrone> droneList = droneMapper.selectList(queryWrapper1);
        Integer droneNum = droneList.size();
        Integer droneOnlineNum = 0;
        List<GetDroneByIdResponseDTO> onlineDrone = new ArrayList<>();
        for (FeisuanDrone feisuanDrone : droneList) {
            Duration duration =Duration.between(feisuanDrone.getModifyTime(), LocalDateTime.now());
            if (feisuanDrone.getStatus() ==1 && duration.toSeconds() <10){
                try {
                    CoordinateTransformUtil.Coordinate coordinate = CoordinateTransformUtil.wgs84ToGcj02(feisuanDrone.getLongitude(), feisuanDrone.getLatitude());
                    feisuanDrone.setLongitude(coordinate.getLongitude());
                    feisuanDrone.setLatitude(coordinate.getLatitude());
                }catch (Exception e){

                }


                GetDroneByIdResponseDTO getDroneByIdResponseDTO= BeanUtil.copyProperties(feisuanDrone, GetDroneByIdResponseDTO.class);
                onlineDrone.add(getDroneByIdResponseDTO);
                droneOnlineNum++;
            }
        }
        device.put("droneOnlineNum",droneOnlineNum);
        device.put("droneNum",droneNum);
        device.put("otherNum",0);
        map.put("device",device);
        map.put("onlineDrone",onlineDrone);

        map.put("onlineDevice",onlineDevice);

        //任务部分
        QueryWrapper<FeisuanInspectionTask> queryWrapper2 = new QueryWrapper<>();

        Long taskTotalNum = inspectionTaskMapper.selectCount(queryWrapper2);
        queryWrapper2.eq("status",2);
        Long taskExNum = inspectionTaskMapper.selectCount(queryWrapper2);

        System.out.println("taskExNum:"+taskExNum);

        List<FeisuanInspectionTask> taskList = inspectionTaskMapper.selectList(queryWrapper2);
        queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("status",1);
        Long taskWaitNum = inspectionTaskMapper.selectCount(queryWrapper2);
        System.out.println("taskWaitNum:"+taskWaitNum);
        queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("status",5);
        Long taskFailNum = inspectionTaskMapper.selectCount(queryWrapper2);

        queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("status",3);
        Long taskCanceledNum = inspectionTaskMapper.selectCount(queryWrapper2);

        Map<String,Object> task = new HashMap<>();
        task.put("taskTotalNum",taskTotalNum);
        task.put("taskExecuteNum",taskExNum);
        task.put("taskWaitNum",taskWaitNum);
        task.put("taskFailNum",taskFailNum);
        task.put("taskCanceledNum",taskCanceledNum);
        task.put("taskExecute",taskList);
        queryWrapper2 = new QueryWrapper<>();
        LocalDate today = LocalDate.now(); // 获取当前日期
        LocalDateTime startOfDay = today.atStartOfDay(); // 当天的开始时间（00:00:00）
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX); // 当天的结束时间（23:59:59）
//        QueryWrapper<FeisuanInspectionTask> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("on_site_inspection_id", feisuanOnSiteInspection.getId());
        queryWrapper2.gt("plan_start_time", startOfDay);
        queryWrapper2.lt("plan_start_time", endOfDay);
        System.out.println(startOfDay);
        System.out.println(endOfDay);
//        queryWrapper2.gt("status",);
        Long todayTask = inspectionTaskMapper.selectCount(queryWrapper2);
        queryWrapper2.eq("status", 4);
        Long todayTaskCompete = inspectionTaskMapper.selectCount(queryWrapper2);
        task.put("todayTask",todayTask);
        task.put("todayTaskCompete",todayTaskCompete);
        map.put("task",task);


        //飞行数据部分
        Map<String,Object> flightMap = new HashMap<>();
        CountFlight flight = flightTaskMapper.countFlight();
        flightMap.put("flightTime",flight.getTime());
        flightMap.put("flightDistance",flight.getDistance());
        flightMap.put("flightNum",flight.getNum());
        flightMap.put("averageTime",flight.getTime()/flight.getNum());
        flightMap.put("averageDistance",Double.valueOf(flight.getDistance().toString())/flight.getNum());
        flightMap.put("taskNum",flight.getNum());
//
        map.put("flight",flightMap);

        return map;
    }


    @Override
    public Page<GetInspectionTaskListResponseDTO> taskList(GetInspectionTaskListRequestDTO getInspectionTaskListRequestDTO) {
        Long startTime = System.currentTimeMillis();
        log.info("开始查询巡检任务列表,当前的时间为:" + LocalDateTime.now());
        QueryWrapper<FeisuanInspectionTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(getInspectionTaskListRequestDTO.getPlanName()), "plan_name", getInspectionTaskListRequestDTO.getPlanName());
        queryWrapper.eq(ObjectUtil.isNotNull(getInspectionTaskListRequestDTO.getStatus()), "status", getInspectionTaskListRequestDTO.getStatus());
        queryWrapper.orderByDesc("plan_start_time");
        log.info("开始查询巡检任务列表数据库操作,当前的时间为:" + LocalDateTime.now());
        Page<FeisuanInspectionTask> feisuanInspectionTaskPage = inspectionTaskMapper.selectPage(new Page<>(getInspectionTaskListRequestDTO.getCurrentPage(), getInspectionTaskListRequestDTO.getPageSize()), queryWrapper);
        log.info("巡检列表数据库查询完成");

        List<Long> collect1 = feisuanInspectionTaskPage.getRecords().stream().map(i -> {
            return i.getAirlineId().longValue();
        }).collect(Collectors.toList());

//        R<Map<Long, GetAirportByIdsResponse>> airportByIds = airportApi.getAirportByIds(collect1);


        List<GetInspectionTaskListResponseDTO> collect = feisuanInspectionTaskPage.getRecords().stream().map(i -> {
            GetInspectionTaskListResponseDTO responseDTO = new GetInspectionTaskListResponseDTO();
            responseDTO.setId(i.getId());
            responseDTO.setPlanName(i.getPlanName());
            responseDTO.setStatus(i.getStatus());
            responseDTO.setStartTime(i.getPlanStartTime());
            responseDTO.setEndTime(i.getEndTime());
            responseDTO.setExecuteTime(i.getStartTime());
            responseDTO.setWaypoint(i.getWaypoint());
            responseDTO.setCurrentWaypointIndex(i.getCurrentWaypointIndex());
            GetAirportByIdRequest getAirportByIdRequest = new GetAirportByIdRequest();
            getAirportByIdRequest.setId(i.getAirportId());
            FeisuanAirport feisuanAirport = airportMapper.selectById(i.getAirportId());
            if (ObjectUtil.isNotNull(feisuanAirport)) {
                responseDTO.setAirlineName(feisuanAirport.getAirportName());
            }
            if (i.getErrorCode() != null) {
                if (i.getErrorCode() == 0) {
                    responseDTO.setErrInfo("执行成功");
                } else {
                    if (ObjectUtil.isNotNull(i.getErrorCode())) {
                        responseDTO.setErrInfo(ErrorCodeUtil.getErrorDescription(i.getErrorCode()));
                    } else {
                        responseDTO.setErrInfo(i.getErrorCode().toString());
                    }
                    if (i.getErrorCode() == 1) {
                        responseDTO.setErrInfo(i.getErrorMessage());
                    }
                }
            } else {
                responseDTO.setErrInfo("");
            }


            //TODO这里尽量不要在循环中使用数据库操作，可以优化的
//            FeisuanAirline feisuanAirline = airlineMapper.selectById(i.getAirlineId());
//            if (ObjectUtil.isNotNull(feisuanAirline)) {
//                responseDTO.setAirlineName(feisuanAirline.getAirlineName());
//            }

//            if (ObjectUtil.isNotNull(airportByIds) && ObjectUtil.isNotNull(airportByIds.getData())
//                    && ObjectUtil.isNotNull(airportByIds.getData().get(i.getAirlineId()))) {
//                responseDTO.setAirportName(airportByIds.getData().get(i.getAirlineId()).getAirportName());
//            }

//            R<GetAirportByIdResponse> airportById = airportApi.getAirportById(getAirportByIdRequest);
//            if (ObjectUtil.isNotNull(airportById) && ObjectUtil.isNotNull(airportById.getData())) {
//                responseDTO.setAirportName(airportById.getData().getAirportName());
//            }



            return responseDTO;
        }).collect(Collectors.toList());

        Page<GetInspectionTaskListResponseDTO> getInspectionTaskListResponseDTOPage = MyBatisPlusPageConverter.convertPage(feisuanInspectionTaskPage, GetInspectionTaskListResponseDTO.class);
        getInspectionTaskListResponseDTOPage.setRecords(collect);
        Long endTime = System.currentTimeMillis();
        log.info("巡检任务列表,查询的时间为:" + (endTime - startTime) + "ms 当前时间为:" + LocalDateTime.now());

        return getInspectionTaskListResponseDTOPage;
    }
}
